<template>
  <div class="app-container">
    <el-card>
      <!-- 顶部统计条件 -->
      <div style="display: flex; align-items: center; justify-content: space-between;">
        <div>
          <span style="font-size: 18px; font-weight: bold; color: #2196f3;">警力统计</span>
        </div>
        <div>
          <span style="margin-right: 16px;">统计时间: {{ statDate }}</span>
          <el-button type="text" @click="setToday">今日</el-button>
          <el-date-picker v-model="statDate" type="date" size="small" style="margin-left: 8px;" />
          <span style="margin-left: 24px;">警力类型：</span>
          <el-radio-group v-model="policeType" size="small">
            <el-radio-button label="民警">民警</el-radio-button>
            <el-radio-button label="辅警">辅警</el-radio-button>
          </el-radio-group>
          <el-button type="primary" size="small" style="margin-left: 12px;" @click="fetchData">查询</el-button>
          <el-button type="success" size="small" style="margin-left: 8px;" @click="exportExcel">导出Excel文件</el-button>
        </div>
      </div>
      <!-- 柱状图 -->
      <div style="margin-top: 24px;">
        <div style="font-weight: bold; margin-bottom: 8px;">各部门警力统计 <span style="font-size: 12px; color: #888;">单位：人</span></div>
        <div ref="barChart" style="width: 100%; height: 320px;"></div>
      </div>
      <!-- 统计表格 -->
      <div style="margin-top: 24px;">
        <div style="font-weight: bold; margin-bottom: 8px;">警力统计列表</div>
        <el-table :data="tableData" border style="width: 100%;" v-loading="loading">
          <el-table-column prop="dept" label="所属部门" width="100" fixed />
          <el-table-column label="民警">
            <el-table-column prop="police.total" label="总人数" width="80" />
            <el-table-column prop="police.should" label="应到数" width="80" />
            <el-table-column prop="police.actual" label="实到数" width="80" />
            <el-table-column prop="police.rate" label="实到率" width="80" />
          </el-table-column>
          <el-table-column label="辅警">
            <el-table-column prop="assistant.total" label="总人数" width="80" />
            <el-table-column prop="assistant.should" label="应到数" width="80" />
            <el-table-column prop="assistant.actual" label="实到数" width="80" />
            <el-table-column prop="assistant.rate" label="实到率" width="80" />
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import * as XLSX from 'xlsx';
import { getPoliceStatistics } from '@/api/system/policeStatistics';

export default {
  name: 'EchartsDemo',
  data() {
    return {
      loading: false,
      statDate: new Date().toISOString().slice(0, 10),
      policeType: '民警',
      barChart: null,
      // 统计数据
      stats: []
    };
  },
  computed: {
    tableData() {
      return this.stats;
    },
    chartSeries() {
      // 根据警力类型切换数据
      const key = this.policeType === '民警' ? 'police' : 'assistant';
      return {
        total: this.stats.map(item => item[key].total),
        should: this.stats.map(item => item[key].should),
        actual: this.stats.map(item => item[key].actual)
      };
    },
    deptNames() {
      return this.stats.map(item => item.dept);
    }
  },
  mounted() {
    this.fetchData();
  },
  watch: {
    policeType() {
      this.initBarChart();
    }
  },
  methods: {
    setToday() {
      this.statDate = new Date().toISOString().slice(0, 10);
    },
    
    // 获取统计数据
    fetchData() {
      this.loading = true;
      
      const params = {
        statDate: this.statDate
      };
      
      getPoliceStatistics(params).then(response => {
        if (response.code === 200) {
          this.stats = response.data;
          this.initBarChart();
          this.$message.success('数据加载成功');
        } else {
          this.$message.error('数据加载失败');
        }
      }).catch(error => {
        console.error('获取统计数据失败:', error);
        this.$message.error('数据加载失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    exportExcel() {
      // 构造表头和数据
      const header = [
        '所属部门',
        '民警-总人数', '民警-应到数', '民警-实到数', '民警-实到率',
        '辅警-总人数', '辅警-应到数', '辅警-实到数', '辅警-实到率'
      ];
      const data = this.tableData.map(row => [
        row.dept,
        row.police.total, row.police.should, row.police.actual, row.police.rate,
        row.assistant.total, row.assistant.should, row.assistant.actual, row.assistant.rate
      ]);
      const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '警力统计');
      XLSX.writeFile(wb, `警力统计_${this.statDate}.xlsx`);
    },
    
    initBarChart() {
      if (!this.barChart) {
        this.barChart = echarts.init(this.$refs.barChart);
      }
      
      if (this.stats.length === 0) {
        return;
      }
      
      this.barChart.setOption({
        tooltip: { 
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: { 
          data: ['总人数', '应到数', '实到数'],
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.deptNames,
          axisLabel: {
            rotate: 45,
            fontSize: 10
          }
        },
        yAxis: { 
          type: 'value', 
          name: '人数',
          minInterval: 1
        },
        series: [
          { 
            name: '总人数', 
            type: 'bar', 
            data: this.chartSeries.total, 
            itemStyle: { color: '#1ec6e6' },
            emphasis: {
              itemStyle: {
                color: '#1ec6e6'
              }
            }
          },
          { 
            name: '应到数', 
            type: 'bar', 
            data: this.chartSeries.should, 
            itemStyle: { color: '#2ecb73' },
            emphasis: {
              itemStyle: {
                color: '#2ecb73'
              }
            }
          },
          { 
            name: '实到数', 
            type: 'bar', 
            data: this.chartSeries.actual, 
            itemStyle: { color: '#f6b93b' },
            emphasis: {
              itemStyle: {
                color: '#f6b93b'
              }
            }
          },
        ]
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 24px;
}
</style>
